<template>
    <view>
        <myNavigation ref="navBar"></myNavigation>
        <!-- 搜索框 -->
        <view class="search_container">
            <view class="search_box">
                <view class="search_in iconfont">
                    <input type="text " @confirm="search_btn" v-model="in_value" @focus="getFocus"
                        placeholder="今天想吃点什么？">
                    <text class="iconfont closeIcon" :class="{ hide: in_value === '' }"
                        @tap.stop="clearValue">&#xe690;</text>
                </view>
                <view class="search_btn" @tap.stop="search_btn">搜索</view>
            </view>
        </view>

        <!-- 搜索栏页面 (开发中..完成之后添加！) -->
        <view v-show="!isSearch">
            <!-- 搜索历史模块 -->
            <view class="history_search" :class="{ hide: his_list.length === 0 }">
                <view class="history_h">
                    搜索历史
                    <text class="clearHis" @tap.stop="clearHis">清空</text>
                </view>
                <view class="history_box">
                    <block v-for="(     item, index     ) in      his_list     " :key="index">
                        <view class="history_item" :data-id="item" @tap="searchByName">
                            <text>{{ item }}</text>
                        </view>
                    </block>
                </view>
            </view>

            <!-- 热门搜索模块 -->
            <view class="hots">
                <view class="hot_h">热门搜索</view>
                <view class="hots_box">
                    <block v-for="(     item, index     ) in      hot_list     " :key="index">
                        <view class="hotItem" :data-id="item" @tap="searchByName">
                            <text>{{ item }}</text>
                        </view>
                    </block>
                </view>
            </view>
        </view>

        <!-- 搜索详细信息页面  v-show="isSearch"  -->
        <view class="tabs" v-show="isSearch">
            <view class="tab_head" :class="{ hidden: !isHeaderVisible }">

                <!--  -->
                <block v-for=" (item, index)  in   tabList " :key="index">
                    <!--  -->
                    <view class="tab_head_item" :class="{ active: current_tab === index }" :data-value="index"
                        @tap="handleClick">
                        <text>{{ item.title }} </text>
                    </view>
                </block>


            </view>
            <block v-for="(page, index) in tabPageList" :key="index">
                <view v-if="current_tab === index" class="tab_body">
                    <scroll-view :scroll-y="true" class="scroll_box" @scroll="handleScroll">
                        <view class="tab_body_item">
                            <block v-for="(f_item, food_index) in  page.foodList " :key="food_index"
                                v-if="page.foodList.length!==0">
                                <view class="food_item" @tap=toMenuInfoPage(f_item)>
                                    <view class="food_img">
                                        <image :src=f_item.imgSrc mode="aspectFill" />
                                    </view>
                                    <view class="food_info">
                                        <view class="food_name">{{ f_item.title }}</view>

                                        <view class="food_tag">
                                            <block v-for="(item1, index1) in  f_item.tags  " :key="index1">
                                                <view class="tag_item">{{ item1 }}</view>
                                            </block>
                                        </view>

                                        <view class=" food_data">
                                            <text class="grade">评分:{{ f_item.grade }}</text>
                                            <text class="number">{{ f_item.favoritesNum }}人做过</text>
                                        </view>
                                        <view class="author_name">{{ f_item.authorName }}</view>
                                    </view>
                                </view>
                            </block>
                            <view class="noData_tip" v-if="page.foodList.length===0">暂无该菜谱哦，换个名字搜搜看~</view>
                        </view>
                    </scroll-view>
                </view>
            </block>
        </view>
        <!-- 提示用户登录 -->
        <LoginTip ref="loginTip" v-if="!isLogin"></LoginTip>
    </view>
</template>

<script setup>
    import { ref, onMounted, inject, reactive } from 'vue';
    import Taro, { useRouter, useDidShow } from "@tarojs/taro";
    import './search.scss';
    import myNavigation from "../../../components/myNavigation.vue";
    import LoginTip from "../../../components/LoginTip.vue";

    // 注入配置
    const config = inject('config');
    const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


    // 导航栏信息
    const navBar = ref(null);
    const navigationHome = () => {
        Taro.switchTab({
            url: '../../index/index',
        });
    };
    const setNavBar = () => {
        if (navBar.value) {
            navBar.value.navigationHome = navigationHome;
            navBar.value.navigationTitle = '菜谱搜索';
        }
    }



    /* 搜索模块 */
    const in_value = ref('');
    // 搜索按钮
    const search_btn = () => {
        if (in_value.value === '') return;
        Taro.showLoading({
            title: '加载中...',
            mask: true
        })
        getSelectResult(in_value.value);
        isSearch.value = true
        addSearchHistory();

        console.log('搜索值为：' + in_value.value);

    };
    // 清除搜索值
    const clearValue = () => {
        in_value.value = '';
    }

    /*  搜索历史 */
    // 搜索历史记录
    const his_list = ref([]);
    //  添加历史记录，最多七条，在搜索框的搜索的点击事件中使用
    function addSearchHistory() {

        if (in_value.value.trim() === '') return;

        const index = his_list.value.indexOf(in_value.value);
        if (index !== -1) {
            // 记录已经存在，则移动到第一个位置
            his_list.value.splice(index, 1);
        } else if (his_list.value.length >= 7) {
            // 如果数组满了，则删除最后一个元素

            his_list.value.pop();
        }

        // 将元素添加到
        his_list.value.unshift(in_value.value);
        // 存储到本地记录中
        Taro.setStorageSync('select_history', JSON.stringify(his_list.value));
    }
    const clearHis = () => {
        his_list.value = [];
        Taro.setStorageSync('select_history', '');
    }


    /* 热门搜索 */
    // 热门搜索列表
    const hot_list = ['早饭', '蚝油生菜', '干锅鸡翅虾', '干锅排骨', '猪蹄'];


    // 点击查询函数
    const searchByName = (e) => {

        // 可以根据传递的值来查询
        in_value.value = e.currentTarget.dataset.id
        search_btn();
    }


    /**  搜索详细信息页面*/
    const isSearch = ref(false);
    const getFocus = (e) => {
        isSearch.value = false
    };
    // 隐藏和显示标签页头部(上滑下滑控制)
    const isHeaderVisible = ref(true);
    const lastScrollTop = ref(0);
    const headerHeight = ref(100);
    const handleScroll = (e) => {
        const currentScrollTop = e.detail.scrollTop;
        if (currentScrollTop > lastScrollTop.value) {
            // 向下滚动
            isHeaderVisible.value = false;
        } else {
            // 向上滚动
            isHeaderVisible.value = true;
        }
        lastScrollTop.value = currentScrollTop <= 0 ? 0 : currentScrollTop;
    }


    //标签页标题
    const current_tab = ref(0);
    const tabList = [
        { title: '综合' },
        { title: '评分最高' },
        { title: '做过最多' }
    ];
    // 标签页面列表
    const tabPageList = reactive([
        {
            title: "综合",
            foodList: [
                // {
                //     imgSrc: "https://gitee.com/xi0503/cooking-applet/raw/master/src/userData/img/articles/niuleitiao/18.png",
                //     title: "好吃的牛肉串",
                //     tags: ['好吃', '热搜商品'],
                //     grade: "8.8分",
                //     favoriteNum: "99人做过",
                //     authorName: "yizhixiya"
                // },
            ]
        },
        {
            title: "评分最高",
            foodList: [

            ]
        },
        {
            title: "做过最多",
            foodList: [

            ]
        },
    ]);

    // 点击切换标签页
    function handleClick(e) {
        current_tab.value = e.currentTarget.dataset.value;
    }

    // 食物列表数据
    const foodList = ref();

    // 跳转菜谱详细页面
    const toMenuInfoPage = (item) => {
        if (getIsLogin()) return;
        Taro.navigateTo({
            url: `../menuInfo/menuInfo?recipeId=${item.recipeId}&userId=${curUserId.value}`
        });
    }


    // 获取外来搜索值

    const selectResult = ref();
    const getSearchValue = () => {
        const router = useRouter();
        const searchValue = router.params.searchValue;
        in_value.value = searchValue ? searchValue : '';

        if (in_value.value !== '') {
            search_btn();
        }
    }

    const getSelectResult = (queryString) => {
        Taro.request({
            url: `${baseUrl}/recipe/selectRecipe?queryString=${queryString}`,
            success: (res) => {
                selectResult.value = res.data.data;
                if (Array.isArray(selectResult.value)) {
                    // 解析 tags 并打印 grade 的类型
                    selectResult.value.forEach(item => {
                        try {
                            item.tags = JSON.parse(item.tags);
                        } catch (e) {
                            console.error('JSON parse error:', e);
                        }
                    });

                    // 初始化 tabPageList 中的 foodList
                    tabPageList[0].foodList = [...selectResult.value]; // 复制数组
                    tabPageList[1].foodList = [...selectResult.value].sort((a, b) => parseFloat(b.grade) - parseFloat(a.grade));
                    tabPageList[2].foodList = [...selectResult.value].sort((a, b) => parseInt(b.favoritesNum) - parseInt(a.favoritesNum));
                }
                Taro.hideLoading();
            }
        });
    }


    // 登录弹窗
    const loginTip = ref(null);

    //跳转到登录界面
    const toLoginPage = () => {
        Taro.navigateTo({
            url: `../login/login`,
        })
    }

    // 判断用户是否登录
    const isLogin = ref(false);
    function getIsLogin() {
        if (loginTip.value != null) loginTip.value.toLoginPage = toLoginPage;
        // 通过查看本地是否存放用户id判断用户是否登录
        isLogin.value = !(curUserId.value === "");
        if (!isLogin.value) {
            if (loginTip.value !== null)
                loginTip.value.isHidden = false;
            return true
        } else return false;
    }


    // 存放当前登录用户
    const curUserId = ref('');


    Taro.useDidShow(() => {
        curUserId.value = Taro.getStorageSync('userId')
        if (Taro.getStorageSync('select_history') !== '')
            his_list.value = JSON.parse(Taro.getStorageSync('select_history'));

    })
    onMounted(() => {
        getSearchValue();
        setNavBar();

    });
</script>